package com.wanfajie.smsdistribute.common.listener

import android.support.design.widget.BottomNavigationView
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.support.v4.view.ViewPager
import android.view.MenuItem

class NavigationViewPagerAdapter(fragmentManager: FragmentManager,
                                 private val viewPager: ViewPager,
                                 private val navView: BottomNavigationView,
                                 private val fragmentMap: Map<Int, Fragment>)
    : FragmentPagerAdapter(fragmentManager), ViewPager.OnPageChangeListener,
        BottomNavigationView.OnNavigationItemSelectedListener {

    private var listener : ((Int, MenuItem, Fragment) -> Unit)? = null
    private val navItemIds = ArrayList<Int>(navView.menu.size())
    val currentFragment : Fragment get() = getItem(viewPager.currentItem)

    init {
        viewPager.adapter = this
        viewPager.addOnPageChangeListener(this)
        navView.setOnNavigationItemSelectedListener(this)

        for (i in 0 until navView.menu.size()) {
            navItemIds.add(navView.menu.getItem(i).itemId)
        }
    }

    fun setOnChangedListener(v: (Int, MenuItem, Fragment) -> Unit) {
        listener = v
    }

    override fun getItem(p0: Int): Fragment {
        val navId = navItemIds[p0]
        return fragmentMap.getValue(navId)
    }

    override fun getCount(): Int {
        return navView.menu.size()
    }

    override fun onNavigationItemSelected(p0: MenuItem): Boolean {
        val index = navItemIds.indexOf(p0.itemId)

        // 设置currentItem会连带调用onPageSelected,
        // 所以listener放在onPageSelected中调用
        viewPager.currentItem = index

        return true
    }

    override fun onPageSelected(p0: Int) {

        for (i in 0 until navView.menu.size()) {
            navView.menu.getItem(i).isChecked = false
        }

        val item = navView.menu.getItem(p0)
        item.isChecked = true
        listener?.apply {
            invoke(p0, item, getItem(p0))
        }
    }

    override fun onPageScrollStateChanged(p0: Int) = Unit
    override fun onPageScrolled(p0: Int, p1: Float, p2: Int) = Unit
}